package com.lanou.elh.members.service.impl;

import com.lanou.elh.members.entity.Address;
import com.lanou.elh.members.entity.Member;
import com.lanou.elh.members.mapper.MemberMapper;
import com.lanou.elh.members.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;


@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Override
    public void register(Member member) {
        Member regisMember = memberMapper.findMemberByUsername(member);
        //获取当前时间
        Date created = new Date();
        //如果数据库没有该用户 可以注册
        if(regisMember==null){
            String pwd = member.getPassword();

            // 生成一个MD5加密计算摘要
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(pwd.getBytes());
                String password = new BigInteger(1, md.digest()).toString(16);
                member.setPassword(password);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }

            Date updated = new Date();
            member.setCreated(created);
            member.setUpdated(updated);
            memberMapper.insertMember(member);
        }
    }

    @Override
    public void addAddress(Address address) {
        memberMapper.insertAddress(address);
    }

    @Override
    public void deleteAddress(Integer addressId) {
        memberMapper.deleteAddressByAddressId(addressId);
    }

    @Override
    public void editAddress(Address address) {
        memberMapper.updateAddress(address);
    }

    @Override
    public void editMember(Member member) {
        memberMapper.updateMember(member);
    }
}
